<?php
/**
 * 获取配置数据
 */
declare(strict_types=1);

namespace Libraries;

class Config
{
    private static $arrData = null; // 存放配置数据，保存在内存中
    private static $strEnv = null; // 当前运行环境
    private static $strMachName = null; // 机器唯一标识
    private static $strAppName = null;

    /**
     * 获取APP名称
     * @return string
     */
    public static function getAppName(): string
    {
        if (is_null(self::$strAppName)) {
            self::$strAppName = defined('APP_NAME') ? APP_NAME : '';
        }
        return self::$strAppName;
    }

    /**
     * 取机器唯一标识
     * @return string
     */
    public static function getMachName(): string
    {
        if (is_null(self::$strMachName)) {
            self::$strMachName = md5(self::getAppName() . '|' . Helper::jsonEncode(swoole_get_local_mac()));
        }
        return self::$strMachName;
    }

    /**
     * 取配置数据
     * @param string $strKey 空,key,keyA:keyB:keyC
     * @param mixed $default
     * @return string|array
     */
    public static function get(string $strKey = '', $default = null)
    {
        is_null(self::$arrData) && self::loadData();
        $strKey = trim($strKey);
        if ('' === $strKey) { // 取全部配置数据
            return self::$arrData;
        }
        $arrKey = explode(':', trim($strKey, ':'));
        $re = self::$arrData;
        foreach ($arrKey as $strKey) {
            $re = $re[$strKey] ?? null;
            if (is_null($re)) {
                break;
            }
        }
        if (is_null($re)) {
            return $default;
        }
        return $re;
    }

    /**
     * 取当前的运行环境
     * @return string|null
     */
    public static function getEnv(): ?string
    {
        if (is_string(self::$strEnv)) {
            return self::$strEnv;
        }
        if (!defined('APP_PATH')) {
            return null;
        }
        foreach (['_keep', ''] as $s) {
            $strWhichFile = APP_PATH . '/configs/which' . $s . '.php';
            if (file_exists($strWhichFile) && is_file($strWhichFile)) {
                self::$strEnv = include($strWhichFile);
                break;
            }
        }
        is_string(self::$strEnv) || self::$strEnv = '';
        return self::$strEnv;
    }

    /**
     * 加载数据
     * @return void
     */
    private static function loadData(): void
    {
        $strConfigFile = APP_PATH . '/configs/' . self::getEnv() . '.php';
        if (file_exists($strConfigFile) && is_file($strConfigFile)) {
            self::$arrData = include($strConfigFile);
        }
        is_array(self::$arrData) || self::$arrData = [];
    }
}
